<template>
  <div>
    <div class="header clear-fix">
      <span class="img-left" @click="handelClick">
        <img src="../assets/img/fanhui.png" alt="" />
      </span>
      <span class="cart">
        <p>购物车</p>
      </span>
      <div class="img-right">
        <img src="../assets/img/tuceng.png" alt="" />
      </div>
    </div>

    <van-checkbox-group v-model="checked" ref="checkboxGroup" icon-size="18">
      <div
        class="products clear-fix"
        v-for="(item, index) in cartList"
        :key="item"
      >
        <van-swipe-cell :before-close="beforeClose" :name="item.id">
          <div class="input">
            <van-checkbox
              :name="item.id"
              @click="fn(item.flag, index, item.id)"
            ></van-checkbox>
          </div>
          <div class="figure">
            <img :src="item.url" alt="" />
          </div>

          <div class="name">
            <em>现货</em>
            <p>{{ item.title }}</p>
            <div class="money-img">
              <img src="../assets/img/money.png" alt="" />
              <span>{{ item.price * item.num }}</span>
            </div>
          </div>

          <div class="numbers" @click="handelClicks(item.id)">
            <van-stepper
              v-model="item.num"
              theme="round"
              button-size="22"
              disable-input
            />
          </div>

          <template #right>
            <van-button
              square
              text="删除"
              type="danger"
              class="delete-button"
            />
          </template>
        </van-swipe-cell>
      </div>
    </van-checkbox-group>

    <div class="empty-box" v-show="cartList.length == 0">
      <img
        src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.zcool.cn%2Fcommunity%2F0173c45a17ec58a80120908d7c5b4b.jpg%401280w_1l_2o_100sh.jpg&refer=http%3A%2F%2Fimg.zcool.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1637499972&t=01a7f49cbd2c950b4acb068d3ae76ca4"
        alt=""
        @click="goIndex"
        class="emptyCart"
      />
    </div>

    <div class="clear">
      <van-submit-bar :price="sum" button-text="提交订单" @submit="showPopup1">

        <van-checkbox v-model="checked1" @click="checkAll">全选</van-checkbox>

        <van-popup v-model:show="show1" position="bottom"
          ><van-password-input
            :value="value1"
            :focused="showKeyboard"
            info="请输入支付密码"
            :error-info="errorInfo"
            @focus="showKeyboard = true" />
          <!-- 数字键盘 -->

          <van-number-keyboard
            v-model="value1"
            :show="showKeyboard"
            @blur="showKeyboard = false"
        /></van-popup>

      </van-submit-bar>
    </div>
  </div>
</template>

<script>
import {
  Stepper,
  SubmitBar,
  Checkbox,
  CheckboxGroup,
  SwipeCell,
  Button,
  Dialog,
  PasswordInput,
  NumberKeyboard,
  Popup,
  Toast,
} from "vant";

import { ref, computed, watch } from "vue";
import { useRouter } from "vue-router";
export default {
  setup() {
    const checked1 = ref(false);

    const router = useRouter();

    const count = ref(3);

    const checked = ref([]);
    const checkboxGroup = ref(null);

    const show1 = ref(false);
    const value1 = ref("");
    const showKeyboard = ref(true);
    const errorInfo = ref("");

    const num = ref(0);
    const cartList = ref(JSON.parse(sessionStorage.getItem("cart")) || []);

    cartList.value = cartList.value.map((el) => {
      el.flag = false;
      return el;
    });

    let checkList = ref(
      cartList.value.map((el) => {
        return el.flag;
      })
    );

    const goIndex = function () {
      router.push("/home/index");
    };

    const sum = computed(() => {
      let price = 0;

      for (let index in cartList.value) {
        if (checkList.value[index]) {
          price += cartList.value[index].num * cartList.value[index].price;
        }
      }

      return price * 100;
    });

    const checkAll = () => {
      console.log(checked.value.length);
      checkboxGroup.value.toggleAll(checked1.value);

      if(cartList.value.length){
        console.log(cartList.value);
        for(let val of cartList.value){
          val.flag=checked1.value;
        }
      };

      console.log(checked.value);

      for (let key in checkList.value) {
        checkList.value[key] = checked1.value;
      }
    };

    const handelClicks = (id) => {
      let stick = JSON.parse(sessionStorage.getItem("cart"));

      if (stick.some((el) => el.id === id)) {
        let _index = stick.findIndex((elm) => elm.id == id);

        let count = parseInt(stick[_index].num);

        count = cartList.value[_index].num;

        console.log(count);

        stick[_index].num = count;

        console.log(stick[_index].num);

        sessionStorage.setItem("cart", JSON.stringify(stick));

        // console.log(stick[_index].num);
        //找不到直接添加
      }
    };

    const handelClick = () => {
      router.go(-1);
    };

    const fn = (flag, index) => {
      checkList.value[index] = !checkList.value[index];

      cartList.value[index].flag=!cartList.value[index].flag;

      if (checked.value.length == count.value) {
        checked1.value = true;
        console.log(checked1.value);
      } else {
        checked1.value = false;
      }

    };

    const beforeClose = ({ name, position }) => {
      switch (position) {
        case "left":
        case "cell":
        case "outside":
          return true;
        case "right":
          return new Promise((resolve) => {
            Dialog.confirm({
              title: "确定删除吗？",
            }).then(() => {
              console.log(name);

              cartList.value = cartList.value.filter((item) => item.id != name);
              console.log(name);
              //删除

              let stick = JSON.parse(sessionStorage.getItem("cart"));

              if (stick.some((el) => el.id === name)) {
                let _index = stick.findIndex((elm) => elm.id == name);

                stick = stick.filter((item, index) => index != _index);

                sessionStorage.setItem("cart", JSON.stringify(stick));

                // console.log(stick[_index].num);
                //找不到直接添加
              }

              resolve();
            });
          });
      }
    };

    const showPopup1 = () => {
      if (localStorage.getItem("token")) {
        fetch("http://2107.wqdp.com.cn/users/token", {
          method: "POST",
          body: JSON.stringify({
            token: localStorage.getItem("token"),
          }),
          headers: {
            "content-type": "application/json",
          },
        })
          .then((response) => response.json())
          .then((res) => {
            //判断token是否正确
            console.log(res.status);
            if (res.status == 0) {
              show1.value = true;
            } else {
              Toast.fail("用户信息错误");
              localStorage.removeItem("token");
              router.push("/login");
            }
          });
      } else {
        router.push("/login");
      }
    };

    watch(value1, (newVal) => {
      if (newVal.length === 6) {
        fetch("http://2107.wqdp.com.cn/users/token", {
          method: "POST",
          body: JSON.stringify({
            token: localStorage.getItem("token"),
            zfmm: newVal,
          }),
          headers: {
            "content-type": "application/json",
          },
        })
          .then((response) => response.json())
          .then((res) => {
            //密码正确往订单中传输数据
            let list = cartList.value.filter((el) => el.flag == true);
            console.log(list);

            checkList.value

            if (res.status == 0) {
              Toast.success("支付成功");
              //传输数据变量

              // const stickdetail = list;

              //获取本地存储
                let stick = JSON.parse(sessionStorage.getItem("cart"));
                //判定是否有本地储存
                // if (stick) {
                  
                // } else {
                //   //没有本地存储的话直接设置
                //   stick = [];
                //   stick.push(stickdetail);
                // }
                sessionStorage.setItem("cart", JSON.stringify(stick));
                router.push("/order");
              } else {
                Toast.fail("支付密码错误");
                value1.value = "";
            }
          });
      } else {
        errorInfo.value = "";
      }
    });

    return {
      checked,
      checked1,
      checkboxGroup,
      checkAll,
      num,
      fn,
      cartList,
      beforeClose,
      handelClicks,
      sum,
      checkList,
      handelClick,
      goIndex,
      showPopup1,
      show1,
      value1,
      showKeyboard,
      errorInfo,
    };
  },

  components: {
    VanStepper: Stepper,
    VanSubmitBar: SubmitBar,
    VanCheckbox: Checkbox,
    vanCheckboxGroup: CheckboxGroup,
    vanButton: Button,
    vanSwipeCell: SwipeCell,
    vanPasswordInput: PasswordInput,
    vanNumberKeyboard: NumberKeyboard,
    vanPopup: Popup,
  },
};
</script>

<style lang="less" scoped>
@color: #f04a3a;

.empty-box {
  width: 375px;
  height: 620px;
  background-color: white;
}
.emptyCart {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
  width: 250px;
}
.goods-card {
  margin: 0;
  background-color: white;
}

.delete-button {
  height: 100%;
}

.clear-fix:after {
  content: "";
  height: 0;
  clear: both;
  overflow: hidden;
  display: block;
  visibility: hidden;
}
.header {
  width: 375px;
  height: 40px;
  background: #ffffff;
  // position: fixed;
  // top: 0;
  // overflow: hidden;

  .img-left {
    display: inline-block;
  }
  .img-left img {
    width: 8px;
    height: 14px;
    margin: 12px 0 0 15px;
  }
  .img-right {
    float: right;
  }
  .img-right img {
    width: 14px;
    height: 14px;
    margin: 12px 12px 0 0;
  }
  .cart {
    display: inline-block;
    width: 300px;
    text-align: center;
  }
  .cart p {
    display: inline-block;
    font-size: 18px;
    font-family: PingFang SC;
    font-weight: bold;
    color: #000000;
    line-height: 18px;
    padding-left: 20px;
  }
}

.products {
  // width: 375px;
  height: 109px;
  background: #fff;
  border-radius: 14px;
  margin: 10px 10px 10px 10px;
  position: relative;

  .input .van-checkbox {
    float: left;
    width: 18px;
    height: 18px;
    margin: 45px 10px 0 10px;
  }
}

.figure {
  float: left;
  width: 82px;
  height: 82px;
  background: #b3b3b3;
  border-radius: 9px;
  margin-top: 15px;
  margin-right: 10px;

  > img {
    width: 82px;
    height: 82px;
  }
}
.name {
  height: 109px;
  overflow: hidden;
}

.name em {
  display: inline-block;
  border: 1px solid @color;
  border-radius: 5px;
  width: 30px;
  height: 15px;
  font-size: 8px;
  color: @color;
  text-align: center;
  margin-right: 10px;
}
.name p {
  display: inline-block;
  font-size: 14px;
  font-family: Adobe Heiti Std;
  font-weight: normal;
  color: #333333;
  line-height: 18px;
  width: 220px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.money-img {
  margin-top: 15px;
  width: 150px;
  float: left;

  > img {
    width: 7px;
    height: 9px;
    margin-right: 3px;
  }
  > span {
    font-size: 18px;
    font-family: Helvetica;
    font-weight: bold;
    color: @color;
  }
}
.numbers {
  position: absolute;
  bottom: -40px;
  right: 10px;
}
.clear {
  position: fixed;
  bottom: 0;
}
.van-swipe-cell__right::after {
  height: 150px;
}
/deep/.van-popup--bottom {
  padding-top: 50px;
  height: 500px;
}
</style>
